package handle

import (
	"log"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/plugin/dbresolver"
)

var DB *gorm.DB // 统一入口

func InitGorm() {
	dsnMaster := ApolloConfigCache.GetValue("master-db")
	dsnSlave := ApolloConfigCache.GetValue("slave-db")
	if dsnMaster == "" || dsnSlave == "" {
		log.Fatalf("master-db or slave-db dsn empty")
	}

	var err error
	// 先连 Master
	DB, err = gorm.Open(mysql.Open(dsnMaster), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Warn),
	})
	if err != nil {
		log.Fatalf("open master fail: %v", err)
	}

	// 注册读写分离插件
	_ = DB.Use(dbresolver.Register(dbresolver.Config{
		Sources:  []gorm.Dialector{mysql.Open(dsnMaster)}, // 写
		Replicas: []gorm.Dialector{mysql.Open(dsnSlave)},  // 读
		Policy:   dbresolver.RandomPolicy{},
	}).
		SetConnMaxIdleTime(time.Hour).
		SetConnMaxLifetime(time.Hour).
		SetMaxIdleConns(10).
		SetMaxOpenConns(100),
	)

	// 探活
	sqlDB, _ := DB.DB()
	if err := sqlDB.Ping(); err != nil {
		log.Fatalf("ping db fail: %v", err)
	}
}
